package com.mindskip.xzs.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.repository.ExamMapper;
import com.mindskip.xzs.repository.NewExamPaperAnswerMapper;
import com.mindskip.xzs.repository.NewExamPaperQuestionCustomerAnswerMapper;
import com.mindskip.xzs.service.ExamPaperService;
import com.mindskip.xzs.service.ExamService;
import com.mindskip.xzs.service.NewExamPaperService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.IdNameKV;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperPageReq;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperPageRequestVM;
import com.mindskip.xzs.viewmodel.admin.exam.ExamResponseVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@RestController("AdminExamPaperController")
@RequestMapping(value = "/api/admin/exam/paper")
public class ExamPaperController extends BaseApiController {

    private final ExamPaperService examPaperService;
    @Resource
    private NewExamPaperService newExamPaperService;
    @Resource
    private ExamMapper examMapper;
    @Resource
    private ExamService examService;
    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    public ExamPaperController(ExamPaperService examPaperService) {
        this.examPaperService = examPaperService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamResponseVM>> pageList(@RequestBody(required = false) ExamPaperPageReq model) {
        if (model == null) {
            model = new ExamPaperPageReq();
            model.setPageIndex(1);
            model.setPageSize(10);
        }
        PageInfo<ExamPaper> pageInfo = examPaperService.page(model);
        PageInfo<ExamResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamResponseVM vm = modelMapper.map(e, ExamResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            vm.setScore(ExamUtil.scoreToVM(e.getScore()));
            return vm;
        });
        return RestResponse.ok(page);
    }



    @RequestMapping(value = "/taskExamPage", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamResponseVM>> taskExamPageList(@RequestBody ExamPaperPageRequestVM model) {
        PageInfo<ExamPaper> pageInfo = examPaperService.taskExamPage(model);
        PageInfo<ExamResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamResponseVM vm = modelMapper.map(e, ExamResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }



    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<ExamPaperEditRequestVM> edit(@RequestBody @Valid ExamPaperEditRequestVM model) {
        ExamPaper examPaper = examPaperService.savePaperFromVM(model, getCurrentUser());
        ExamPaperEditRequestVM newVM = examPaperService.examPaperToVM(examPaper.getId());
        examPaperService.updatePaperKVInCache();
        return RestResponse.ok(newVM);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<ExamPaperEditRequestVM> select(@PathVariable Integer id) {
        ExamPaperEditRequestVM vm = examPaperService.examPaperToVM(id);
        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        NewExamPaper examPaper = newExamPaperService.getById(id);
        if (examPaper != null) {
            newExamPaperService.updateById(examPaper.setDeleted(true));
        }
        List<Exam> exams = examMapper.selectList(new LambdaQueryWrapper<Exam>().eq(Exam::getPaperId, id));
        // 删除考试
        if (CollectionUtil.isNotEmpty(exams)) {
            exams.forEach(exam -> examService.updateById(exam.setDeleted(true)));
        }

      /*  // 删除答案
        newExamPaperQuestionCustomerAnswerMapper.delete(
                new LambdaUpdateWrapper<ExamPaperQuestionCustomerAnswer>()
                        .eq(ExamPaperQuestionCustomerAnswer::getExamPaperId, id)
        );
        newExamPaperAnswerMapper.delete(
                new LambdaUpdateWrapper<ExamPaperAnswer>()
                        .eq(ExamPaperAnswer::getExamPaperId, id)
        );*/
        examPaperService.updatePaperKVInCache();

        // 记录日志
        User user = getCurrentUser();
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = String.format("%s删除试卷【%s】", user.getUserName(), examPaper.getName());
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));

        return RestResponse.ok();
    }

    /**
     * 查询试卷kv列表
     */
    @RequestMapping(value = "/list/kv", method = RequestMethod.GET)
    public RestResponse<List<IdNameKV>> queryPaperKVListInCache(@RequestParam(required = false, value = "keyword") String keyword) {
        return RestResponse.ok(examPaperService.queryPaperKVListInCache(keyword));
    }
}
